package com.cmy.lesson04;

import com.cmy.lesson2.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestTransaction {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            //关闭数据库的自动提交功能,自动开始事务
            conn.setAutoCommit(false);

            String sql1 = "update `acount` set `money` = `money`-500 where `name` = 'A'";
            pst = conn.prepareStatement(sql1);
            pst.executeUpdate();

            String sql2 = "update `acount` set `money` = `money`+500 where `name` = 'B'";
            pst = conn.prepareStatement(sql2);
            pst.executeUpdate();

            //业务完毕,提交事务
            conn.commit();
            System.out.println("Success");
        } catch (SQLException throwables) {
            try {
                conn.rollback();//如果失败,回滚事务
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            JdbcUtils.release(conn,pst,rs);
        }

    }
}

    